# 文件名: modules/food.py
# Keep this file the same
import pygame
import random
from .utils import get_random_grid_position, draw_grid_cell

'''食物类，包含普通和有毒食物'''
class FoodManager:
    def __init__(self, cfg):
        self.cfg = cfg
        self.food_pos = None
        self.poison_pos = None

    def _is_safe_spawn(self, pos, snake_coords, traps, other_food_pos=None):
        """检查生成位置是否安全（不在蛇、陷阱、其他食物上）"""
        if pos in snake_coords:
            return False
        if pos in traps:
            return False
        if other_food_pos and pos == other_food_pos:
            return False
        # Ensure not spawning outside grid (should be handled by get_random_grid_position)
        if not (0 <= pos[0] < self.cfg.GRID_WIDTH and 0 <= pos[1] < self.cfg.GRID_HEIGHT):
             return False
        return True

    def spawn_food(self, snake_coords, traps):
        """生成普通食物"""
        attempts = 0
        max_attempts = self.cfg.GRID_WIDTH * self.cfg.GRID_HEIGHT # Avoid infinite loop
        while attempts < max_attempts:
            pos = get_random_grid_position(self.cfg)
            # 确保不与蛇、陷阱、毒食物重叠
            if self._is_safe_spawn(pos, snake_coords, traps, self.poison_pos):
                self.food_pos = pos
                return self.food_pos
            attempts += 1
        # Fallback if no safe position found (highly unlikely unless grid is full)
        print("Warning: Could not find a safe place for food!")
        self.food_pos = None # Or handle this case differently
        return None


    def spawn_poison(self, snake_coords, traps):
        """生成有毒食物"""
        attempts = 0
        max_attempts = self.cfg.GRID_WIDTH * self.cfg.GRID_HEIGHT
        while attempts < max_attempts:
            pos = get_random_grid_position(self.cfg)
             # 确保不与蛇、陷阱、普通食物重叠
            if self._is_safe_spawn(pos, snake_coords, traps, self.food_pos):
                self.poison_pos = pos
                return self.poison_pos
            attempts += 1
        print("Warning: Could not find a safe place for poison!")
        self.poison_pos = None
        return None


    def draw(self, screen):
        """绘制所有食物"""
        if self.food_pos:
            draw_grid_cell(screen, self.food_pos, self.cfg.FOOD_COLOR, self.cfg)
        if self.poison_pos:
            draw_grid_cell(screen, self.poison_pos, self.cfg.POISON_FOOD_COLOR, self.cfg)

    def get_food_pos(self):
        return self.food_pos

    def get_poison_pos(self):
        return self.poison_pos

    def clear_poison(self):
        """移除毒食物（例如在非毒物关卡）"""
        self.poison_pos = None